<template>
  <div class="wrap">
    <div>
      <el-upload class="upload-demo"
                 ref="upload"
                 @hook:mounted="rewrite"
                 :auto-upload="false"
                 :on-change="getFile"
                 :on-remove="removeFile"
                 :limit="fileLimitNum"
                 :on-exceed="handleExceed"
                 @dragenter.native.stop.prevent
                 @dragover.native.stop.prevent
                 @drop.native.stop.prevent="handleFileDrop($event)">
        <div class="upload-demo-info">
          <em class="el-icon-upload upload-icon"/>
          <div class="el-upload__text">{{ $t('message.PointCloud.clickSelect') }}</div>
        </div>
      </el-upload>
      <div v-if="errorMessage !== ''" class="text-danger mt-2">{{ errorMessage }}</div>
    </div>

    <div class="d-flex align-items-center">
      <label class="el-form-item__label">{{ $t('message.PointCloud.maxLength') }}：</label>
      <el-input v-model="searchRadius" min="0" step="0.1" type="number" @change="changeRadius()" :disabled="isAutoSearchRadius"/>
      <label class="label">mm</label>
    </div>

    <div class="d-flex mt-2 align-items-center">
      <el-checkbox v-model="isAutoSearchRadius">
        {{$t('message.PointCloud.isAutoSearchRadius')}}
      </el-checkbox>
    </div>

    <div class="btn">
      <el-button type="primary" :disabled="errorMessage !== '' || files.length === 0 || searchRadius <=0.0001"
                 @click="uploadFile()">
        {{ $t('message.PointCloud.import') }}
      </el-button>
      <el-button @click="close">{{ $t('message.PointCloud.close') }}</el-button>
    </div>
  </div>

</template>

<script>
import {ElementType, EntityType} from "../../modeling/TypeDefine"
import {ELEMENT} from "../../../nodeApp/static/lib/vuejs/element-ui";
import {pcCommand} from "../../Command/PointCloudCommand";
import DialogMixin from "./DialogMixin";
import axios from "axios";
import {request} from "../../util/Request";
import {mbdCommand} from "../../Command/MbdCommand";
import pointCloud from "./PointCloud.vue";

export default {
  mixins: [DialogMixin],
  data() {
    return {
      files: [],
      errorMessage: "",
      fileLimitNum: 1,
      totalSize: 0,
      fileSize: 0,
      isPcd: false,
      isMerge: false,
      total: 0,
      isCloudFileType: ['pcd','txt'],
      onlyPcdFile: false,
      searchRadius: 1.0,
      isAutoSearchRadius:false
    }
  },

  mounted() {
    pcCommand.init(400, 400, 200, () => {
    });
  },

  methods: {
    handleFileDrop(event) {
      for (let i = 0; i < event.dataTransfer.items.length; i++) {
        let item = event.dataTransfer.items[i];
        let file = item.getAsFile();
        if (item.webkitGetAsEntry().isDirectory) {
          file.isDirectory = true;
          this.errorMessage = this.$t('message.PointCloud.importType');
        } else {
          file.isDirectory = false;
        }
      }
    },

    getFile(file, fileList) {
      this.files = [];
      this.checkOnlyPcd(fileList);
      this.checkFileList(file, fileList)
    },

    checkOnlyPcd(fileList) {
      this.onlyPcdFile = fileList?.length
          ? fileList?.some(file => {
            let extStartIndex = file.name.lastIndexOf(".");
            let ext = file.name.substring(extStartIndex + 1, file.name.len);
            return ext.toLowerCase() === "pcd"
          }) : false;
    },

    removeFile(file, fileList) {
      this.files = [];
      this.checkOnlyPcd(fileList);
      this.checkFileList(file, fileList)
    },

    rewrite() {
      // 重写ElementUpload
      //rewriteUploadOnDrop(this.$refs.upload)
    },

    checkFileList(file, list) {
      this.errorMessage = '';
      this.fileSize = 0;
      this.totalSize = 0;
      this.isPcd = !!list.some(fileItem => this.isCloudFileType.includes(this.getFileType(fileItem.name).toLowerCase()));
      if (list.length === 0) {
        this.errorMessage = '';
      } else {
        let _list = [];
        list.forEach(fileItem => {
          this.files.push(fileItem.raw);
          this.totalSize += fileItem.size;
          this.fileSize += 1;
          if (!_list.includes(fileItem.name)) {
            _list.push(fileItem.name)
          }
          if (!this.checkFormat(fileItem.name, this.getAcceptTypes) || fileItem.raw.isDirectory) {
            this.errorMessage = this.$t('message.PointCloud.importType');
          }
        });
        if (list.length !== _list.length) {
          this.errorMessage = this.$t('message.PointCloud.existsSameName');
        }
        if (this.fileSize > 1) {
          this.errorMessage = this.$t('message.PointCloud.outLimitCount');
        } else if (this.totalSize > this.getAcceptSize) {
          this.errorMessage = this.$t('message.PointCloud.outLimitSize');
        }
      }
    },

    async uploadFile() {
      if (this.files.length === 1) {
        let scope = this;
        let url = 'pointCloud/downloadMeshGridFile';
        let formData = new FormData();
        formData.append("userName", "admin");
        formData.append("searchRadius", this.searchRadius);
        formData.append("isAutoSearchRadius", this.isAutoSearchRadius);
        formData.append("pcdFile", this.files[0]);

        let config = {
          responseType: 'blob',
          timeout: 50000,
        };

        // 进度开始
        pcCommand.openLoading(this.$t('message.PointCloud.loading'));
        await request.post(url, formData, config).then(res => {
          if (res.status === 200) {
            pcCommand.uploadMeshBlob(res.data, (result) => {
              if (result?.data.length > 0) {
                pcCommand.eventBusAlertMsg(result?.data + "文档创建成功", "success");
                pcCommand.closeActiveCmd();
              } else {
                pcCommand.eventBusAlertMsg("文档创建失败，请检查文件和参数是否正确。", "error");
              }

              //写入浏览器下载-start
              // const uri = window.URL.createObjectURL(new Blob([res.data]));
              // const link = document.createElement('a');
              // link.href = uri;
              // link.setAttribute('download', '123.obj');
              // document.body.appendChild(link);
              // link.click();
              // link.remove();
              // window.URL.revokeObjectURL(uri);
              //写入浏览器下载-end
            });
          } else {
            pcCommand.eventBusAlertMsg("文件上传解析请求出现错误。", "error");
          }
        });

        // 进度结束
        pcCommand.closeLoading();
      } else {
        this.errorMessage = this.$t('message.PointCloud.checkSelectFile');
      }
    },

    getFileType(fileName) {
      let delimiterIndex = fileName.lastIndexOf('.');
      return fileName.substring(delimiterIndex + 1).toLowerCase();
    },

    checkFormat(fileName, acceptTypes) {
      let delimiterIndex = fileName.indexOf('.');
      let fileType = fileName.substring(delimiterIndex + 1).toLowerCase();
      let find = false;
      for (let i = 0; i < acceptTypes.length; ++i) {
        if (fileType.includes(acceptTypes[i])) {
          find = true;
          break;
        }
      }
      return find;
    },

    //超出限制数量的回调
    handleExceed() {
      pcCommand.eventBusAlertMsg("一次只能上传一个文件", "warning");
    },

    changeRadius() {
    },

    changePluginContainerHeight() {
      pcCommand.changePluginContainerHeight({minWidth: this.$el.clientWidth, maxHeight: this.$el.clientHeight})
    },

    close() {
      pcCommand.closeActiveCmd();
    }
  },

  computed: {
    // 类型限制
    getAcceptTypes() {
      let typeList = ["pcd","txt"];
      return typeList;
    },

    // 文件大小限制
    getAcceptSize() {
      return 1024 * 1024 * 5;
    }
  },

  destroyed() {
  }
}

</script>

<style scoped>
.wrap {
  font-size: 12px;
}

.el-upload__text {
  color: #409eff;
  font-size: 15px;
}

el-upload__text:after {
  color: #409eff;
  font-size: 15px;
}

.upload-icon {
  font-size: 2em;
  margin: 0;
  color: #C0C4CC;
}

>>> .el-upload-list {
  max-height: 30vh;
  overflow-y: auto;
}

</style>